<template>
  <div class="page-container">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>会员中心</el-breadcrumb-item>
        <el-breadcrumb-item>会员等级管理</el-breadcrumb-item>
        <el-breadcrumb-item>会员等级设置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item>
            <el-form-item label="创建时间：" prop="startTime" style="margin-right:0 !important">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                placeholder="开始时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="line">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                placeholder="结束时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>
            </el-form-item>
          <el-form-item label="等级名称：">
            <el-input
              v-model.trim="filters.levelName"
              placeholder="请输入等级名称"
              maxlength="80"
              clearable
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button icon="el-icon-search" :label="'搜索'" type="primary" @click="findPageClick(null)" />
          </el-form-item>
          <el-form-item>
            <kt-button :plain="true" :label="'重置'" type="primary" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button label="添加会员等级" type="primary" @click="handleAdd" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-table
            :data="tableList"
            :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
            :highlight-current-row="true"
            :max-height="15000"
            :size="'mini'"
            style="width: 100%"
            class="specialTable"
            :border="false"
            v-loading="loading"
          >
            <el-table-column align="center" label="系数"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="等级名称"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.levelName || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="成长值范围"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.growRangeStart}}-{{ scope.row.growRangeEnd}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="每年扣除"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.yearDeduct || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="所属组织"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.deptName || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.createTime || '-'}}</span>
              </template>
            </el-table-column>
            
            <el-table-column class-name="status-col" align="left" fixed="right" label="操作" width="350" >
              <template slot-scope="scope">
                <kt-button
                  @click="handleDetail(scope.row)" type="text" size="mini" style label="查看">
                </kt-button>
                <kt-button
                  @click="handleEdit(scope.row)" type="text" size="mini" style  label="编辑">
                </kt-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页栏-->
          <div class="toolbar" style="padding:10px;">
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="currentChange"
              :current-page="filters.start"
              :page-size="filters.limit"
              :total="totalSize"
              style="float:right;"
              :page-sizes="[10, 20, 30, 40]"
              @size-change="sizeChange"
            ></el-pagination>
          </div>
      <!--新增编辑界面-->
      <el-dialog
        :title="operation?'新增会员等级':'编辑会员等级'"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        @closed="handleClose"
        class="el-dialog-style"
      >
        <el-form
          :model="dataForm"
          :rules="dataFormRules"
          ref="dataForm"
          :size="size"
          label-position="right"
        >
          
          <el-form-item label="等级名称：" prop="levelName" label-width="107px" class="mb10 w200">
            <el-input
              v-model.trim="dataForm.levelName"
              placeholder="请输入等级名称"
              auto-complete="off"
              clearable
              maxlength="20"
            ></el-input>
          </el-form-item>
          <p class="mb10 font12 colorE7 pl108">最多输入20个字符</p>
          <el-form-item label="成长值范围：" required class="mb30">
              <el-form-item prop="growRangeStart" class="turnInlineBlock noMargin">
                <el-input
                  v-model.trim="dataForm.growRangeStart"
                  @change="checkNumber($event)"
                  maxlength="5"
                  auto-complete="off"
                  :disabled="rangeDis"
                  class=" w98 input__inner-pr10"
                  placeholder="请输入"
                  clearable
                ></el-input>
              </el-form-item>
              <span class="connection">-</span>
              <el-form-item prop="growRangeEnd" class="turnInlineBlock noMargin">
                  <el-input
                    v-model.trim="dataForm.growRangeEnd"
                    @change="checkNumber1($event)"
                    maxlength="5"
                    auto-complete="off"
                    :disabled="rangeDis"
                    class="w98 turnInlineBlock input__inner-pr10"
                    placeholder="请输入"
                    clearable
                    min="0"
                  ></el-input>
              </el-form-item>
              
          </el-form-item>
          <el-form-item label="每年扣除：" prop="yearDeduct" label-width="107px" class="mb120">
            <el-input
              v-model.trim="dataForm.yearDeduct"
              auto-complete="off"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="5"
              placeholder="输入数字"
              min="0"
              clearable
            ></el-input>
            <span class="turnInlineBlock m_l10 color333 font16">成长值</span>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
            :size="size"
            @click.native="dialogVisible = false"
            type="primary"
            plain
            class="btn"
          >{{$t('action.cancel')}}</el-button>
          <el-button
            :size="size"
            type="primary"
            @click.native="submitForm"
            :loading="editLoading"
            class="btn"
          >保存</el-button>
        </div>
      </el-dialog>

    <!--查看弹窗-->
    <el-dialog
      title="查看会员等级"
      :visible.sync="infoDialogVisible"
      :close-on-click-modal="false"
      class="el-dialog-style"
    >
      <el-form
        :model="dataForm"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
        label-position="right"
      >
        <el-form-item prop="deptName" v-show="detailDeptOperate" class="mb30" label-width="15px">
          <span style="color:red">*</span>
          <span class="color333 font16">所属组织：</span>
          <span :disabled="deptDis" class="color333 font16">{{this.dataForm.deptName}}</span>
        </el-form-item>
        <el-form-item label="等级名称：" prop="levelName" label-width="107px" class="mb30 w200">
          <el-input
            v-model.trim="dataForm.levelName"
            placeholder="请输入等级名称"
            :disabled="rangeDis"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="成长值范围：" required class="mb30">
          <el-form-item prop="growRangeStart" class="turnInlineBlock noMargin">
            <el-input
              v-model.trim="dataForm.growRangeStart"
              auto-complete="off"
              :disabled="rangeDis"
              class="w98"
              placeholder="输入成长值区间"
            ></el-input>
          </el-form-item>
          <span class="connection">-</span>
          <el-form-item prop="growRangeEnd" class="turnInlineBlock noMargin">
            <el-input
              v-model.trim="dataForm.growRangeEnd"
              auto-complete="off"
              :disabled="rangeDis"
              placeholder="输入成长值区间"
              class="w98 turnInlineBlock"
            ></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="每年扣除：" prop="yearDeduct" label-width="107px" class="mb120">
          <el-input
            v-model.trim="dataForm.yearDeduct"
            :disabled="rangeDis"
          ></el-input>
          <span class="turnInlineBlock m_l10 color333 font16">成长值</span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          :size="size"
          @click.native="infoDialogVisible = false"
          type="primary"
          plain
          class="btn"
          >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import JicTable from "@/components/jicComponentGallery/MemberGradeTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { format } from "@/utils/datetime";
import { exportExcel } from "@/utils/excel";
export default {
  components: {
    PopupTreeInput,
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var checkGrowRangeStart = (rule, value, callback) => {
      if(this.dataForm.growRangeEnd){
        if(Number.parseInt(this.dataForm.growRangeEnd) < value){
          callback(new Error("成长值范围 开始应小于结束值"));
        }
      }
      this.$refs['dataForm'].clearValidate("growRangeEnd");
      callback();
    };
    var checkGrowRangeEnd = (rule, value, callback) => {
      if(this.dataForm.growRangeStart){
        if(Number.parseInt(this.dataForm.growRangeStart) > value){
          callback(new Error("成长值范围 开始应小于结束值"));
        }
      }
      this.$refs['dataForm'].clearValidate("growRangeStart");
      callback();
    };
    return {
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
      loading:true,
      tableList:[],
      deptDis: true,
      editDeptOperate: false,
      detailDeptOperate: false,
      deptLevel: "母平台",
      deptNames: null,
      operateDis: true,
      deptType: 0,
      rangeDis: false,
      totalSize: 0,
      size: "small",
      filters: {
        levelName: null,
        endTime: null,
        startTime: null,
        storeMember:2,
      },
      columns: [],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      options: {},
      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      infoDialogVisible: false, //是否显示查看界面
      editLoading: false,
      dataFormRules: {
        levelName: [
          { required: true, message: "请输入等级名称", trigger: "blur" }
        ],
        growRangeEnd: [
          { required: true, message: "请输入成长值范围", trigger: "blur" },
          { validator: checkGrowRangeEnd, trigger: "blur" },
        ],
        growRangeStart: [
          { required: true, message: "请输入成长值范围", trigger: "blur" },
          { validator: checkGrowRangeStart, trigger: "blur" },
        ]
      },
      // 新增编辑界面数据
      dataForm: {
        growRangeEnd: null,
        growRangeStart: null
      }
    };
  },
  methods: {
    
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },
    // 换页刷新
    currentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      this.findPage();
    },
    sizeChange(pageSize) {
      this.pageRequest.pageNum = 1;
      this.pageRequest.pageSize = pageSize;
      this.findPage();
    },
  
    //点击搜索，页码重置
    findPageClick(){
      this.pageRequest.pageNum = 1;
      this.findPage();
    },
    // 获取分页数据
    findPage: function(data) {
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.utils.request.queryMemberGradeList(this_.filters, function(res) {
        this_.tableList = res.data.rows;
        this_.totalSize = Number(res.data.total);
        this_.loading=false;
      });
    },
    //弹窗关闭方法
    handleClose() {
      this.$refs.dataForm.resetFields();
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDeptOperate = false;
      this.dialogVisible = true;
      this.operation = true;
      this.dataForm = {};
      this.rangeDis = false;
    },
    // 显示编辑界面
    handleEdit: function(params) {
      this.editDeptOperate = true;
      if (params.deptType == "0") {
        this.deptLevel = "母平台";
      } else if (params.deptType == "1") {
        this.deptLevel = "子平台";
      } else if (params.deptType == "2") {
        this.deptLevel = "商家";
      } else if (params.deptType == "3") {
        this.deptLevel = "店铺";
      }
      this.dialogVisible = true;
      this.operation = false;
      this.dataForm = Object.assign({}, params);
      this.rangeDis = true;
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (
          "" != this.dataForm.growRangeStart &&
          this.dataForm.growRangeStart != null &&
          "" != this.dataForm.growRangeEnd &&
          this.dataForm.growRangeEnd != null
        ) {
          this.dataForm.growRange = 1;
        }
        if (valid) {
          let this_ = this;
          let params = Object.assign({}, this_.dataForm);
          params.storeMember=2;
          params.token = localStorage.getItem("token");
          if (this_.dataForm.id != null) {
            this.utils.request.editMemberGrade(params, function(res) {
              if (res.data == "1") {
                this_.$message({ message: "操作成功", type: "success" });
                this_.$refs["dataForm"].resetFields();
                this_.dialogVisible = false;
                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          } else {
            this.utils.request.addMemberGradeInfo(params, function(res) {
              if (res.data == "1") {
                this_.$message({ message: "操作成功", type: "success" });
                this_.$refs["dataForm"].resetFields();
                this_.dialogVisible = false;
                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          }
        }
      });
    },
    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      this.columns = [
        { prop: "id", label: "ID", minWidth: 100 },
        { prop: "levelName", label: "等级名称", minWidth: 100 },
        {
          prop: "account",
          label: "成长值范围",
          minWidth: 120,
          formatter: function(row, column, cellValue, index) {
            return row.growRangeStart + "-" + row.growRangeEnd;
          }
        },
        {
          prop: "yearDeduct",
          label: "每年扣除",
          minWidth: 100,
          formatter: function(row, column, cellValue, index) {
            if (row.yearDeduct != "") {
              return row.yearDeduct;
            } else {
              return "-";
            }
          }
        },
        { prop: "deptName", label: "所属组织" },
        {
          prop: "deptType",
          label: "组织层级",
          formatter: function(row, column, cellValue, index) {
            if (row.deptType == "0") {
              return "母平台";
            } else if (row.deptType == "1") {
              return "子平台";
            } else if (row.deptType == "2") {
              return "商家";
            } else if (row.deptType == "3") {
              return "店铺";
            }
          }
        },
        { prop: "createTime", label: "创建时间", minWidth: 120 }
      ];
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    resetForm(formName) {
      //需要校验的key
      let keys = ["levelName", "endTime", "startTime"];
      let boo = this.seachTableUtils.checkFromIsNull(this.filters, keys);
      if (!boo) {
        return;
      }
      this.filters = {
        levelName: null,
        endTime: null,
        startTime: null,
        storeMember:2,
      };
      this.findPage();
    },
    checkNumber(value) {
      value = value.replace(/[^0-9]/g, "");
      this.$set(this.dataForm, "growRangeStart", value);
    },
    checkNumber1(value) {
      value = value.replace(/[^0-9]/g, "");
      this.$set(this.dataForm, "growRangeEnd", value);
    },
    //查看详情页面
    handleDetail(params) {
      this.detailDeptOperate = true;
      if (params.deptType == "0") {
        this.deptLevel = "母平台";
      } else if (params.deptType == "1") {
        this.deptLevel = "子平台";
      } else if (params.deptType == "2") {
        this.deptLevel = "商家";
      } else if (params.deptType == "3") {
        this.deptLevel = "店铺";
      }
      this.infoDialogVisible = true;
      this.operation = false;
      this.dataForm = Object.assign({}, params);
      this.rangeDis = true;
    }
  },

  mounted() {
    this.initColumns();
    this.findPage();
  }
};
</script>

<style lang='scss' scoped>

.connection {
  display: inline-block;
  height: 32px;
  line-height: 32px;
}

/deep/ .el-dialog__footer {

  margin-top: 0 !important;
}
.mb120 {
  margin-bottom: 120px;
}

/deep/ .w98 {
  width: 90px !important;
  /deep/ .el-input__inner {
    width: 90px !important;
  }
}
.noMargin {
  margin-bottom: 0 !important;
}

.input__inner-pr10{
  /deep/ .el-input__inner{
    padding-right: 10px !important;
  }
}
.colorE7 {
  color: #ffbf5e !important;
}
.mb10 {
  margin-bottom: 10px !important;
}
.pl127 {
  padding-left: 127px !important;
}
.pl108{
  padding-left: 108px !important;
}
</style>
